<?php

namespace app\admin\controller;

use think\Env;
use think\Request;
use app\common\model\Admin as AdminModel;
use app\common\model\AuthRole;
use app\common\server\Code;

class admin extends Base
{
    public function index()
    {
        $where= [];
        $username = request()->get('username');
        $role_id = request()->get('role_id');
        $username && $where[] = ['username','like',"%".$username."%"];
        $role_id  && $where[] = ['role_id','=',$role_id] ;
        $list= AdminModel::getList($where);
        $role_list = AuthRole::getList();
        $this->assign("list",$list);
        $this->assign("role_list",$role_list);
        return $this->fetch();
    }

    public function add(Request $request)
    {
        if($request->isPost()){
            $params = $request->post();
            $validateResult=$this->validateData('admin','add');
            if($validateResult!==true) return apiReturn(Code::$error,$validateResult);
            $result=$admin = AdminModel::create($params);
            if($result) return apiReturn();
            return apiReturn(Code::$error);
        }else{
            $roles = AuthRole::getListByStatus();
            $this->assign("roles",$roles);
            return $this->fetch();
        }
    }

    public function edit(Request $request,$id)
    {
        try{
            if($request->isPost()){
                $params = $request->param();
                $validateResult=$this->validateData('admin','edit',$params);
                if($validateResult!==true) return apiReturn(Code::$error,$validateResult);

                $info = AdminModel::get($id);
                if(!$info) return apiReturn(Code::$error);
                $info->role_id = $params['role_id'];
                $info->remark = $params['remark'];
                $info->save();
                return apiReturn();
            }else{
                $info = AdminModel::find($id);
                $roles = AuthRole::getListByStatus();
                $this->assign("info",$info);
                $this->assign("roles",$roles);
                return $this->fetch();
            }
        }catch (\Exception $e){
            return apiReturn(Code::$error,$e->getMessage());
        }

    }

    public function delete($id)
    {
        $result=AdminModel::destroy($id);
        if($result) return apiReturn();
        return apiReturn(Code::$error,"删除失败");
    }

    public function change_status($id){
        $status = request()->param('status');
        $result = AdminModel::where('id',$id)->update(['status'=>(int) !$status]);
        if($result) return apiReturn();
        return apiReturn(Code::$error);
    }
}
